package com.ruoyi.auth.integration.authenticator;

import com.ruoyi.auth.config.properties.ValidateProperties;
import com.ruoyi.auth.constants.ValidateSubjectEnum;
import com.ruoyi.auth.api.model.dto.UserLoginInfoDto;
import com.ruoyi.auth.integration.IntegrationAuthentication;
import com.ruoyi.auth.service.UserLoginInfoServiceImpl;
import com.ruoyi.auth.verification.service.VerificationCodeService;
import com.ruoyi.common.core.exception.BaseException;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.web.component.LocaleMessageSourceHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;

/**
 * 默认登录处理
 *
 * @author LIQIU
 * @date 2018-3-31
 **/
@Component
@Primary
@Slf4j
public class UsernamePasswordAuthenticator extends AbstractPreparableIntegrationAuthenticator {

    @Autowired
    public UserLoginInfoServiceImpl userLoginInfoServiceImpl;

    @Autowired
    private VerificationCodeService verificationCodeService;

    @Autowired
    private ValidateProperties validateProperties;

    @Autowired
    private LocaleMessageSourceHandler sourceHandler;


    @Override
    public UserLoginInfoDto authenticate(IntegrationAuthentication integrationAuthentication) {
        //获取授权类别
        String userCategory = integrationAuthentication.getUserCategory();
        //获取用户名，实际值是手机号
        String username = integrationAuthentication.getUsername();
//        String password = integrationAuthentication.getAuthParameter("password");
        log.info("{}开始登陆:{}", username);
        UserLoginInfoDto userLoginInfo = userLoginInfoServiceImpl.getUserApiService(userCategory).getUserInfo(username);
        return userLoginInfo;
    }

    @Override
    public void prepare(IntegrationAuthentication integrationAuthentication) {
        if (validateProperties.isEnableValidateCode()) { //当开启了验证码校验
            String code = integrationAuthentication.getAuthParameter("code");
            String codeToken = integrationAuthentication.getAuthParameter("code_token");
            String subject = ValidateSubjectEnum.IMAGE.getCode();
            boolean result = verificationCodeService.validate(codeToken, code, subject);
            if (!result) {
                throw new BaseException(sourceHandler.getMessage("VERIFICATION_CODE_EXCEPTION")).setCode("400").setStatus(400);
            }
        }

    }

    @Override
    public boolean support(IntegrationAuthentication integrationAuthentication) {
        return StringUtils.isEmpty(integrationAuthentication.getAuthType());
    }
}
